package cn.liuhaihua.web.service.impl;

import cn.liuhaihua.web.document.WpPostsDocument;
import cn.liuhaihua.web.repository.WpPostsDocumentRepository;
import cn.liuhaihua.web.service.EsSearchService;
import com.alibaba.fastjson.JSON;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * elasticsearch 搜索引擎 service实现
 * @author zhoudong
 * @version 0.1
 * @date 2018/12/13 15:33
 */
@Service
public class EsSearchServiceImpl extends BaseSearchServiceImpl<WpPostsDocument> implements EsSearchService {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;
    @Resource
    private WpPostsDocumentRepository WpPostsDocumentRepository;

    @Override
    public void save(WpPostsDocument ... WpPostsDocuments) {
        elasticsearchTemplate.putMapping(WpPostsDocument.class);
        if(WpPostsDocuments.length > 0){
            /*Arrays.asList(WpPostsDocuments).parallelStream()
                    .map(WpPostsDocumentRepository::save)
                    .forEach(WpPostsDocument -> log.info("【保存数据】：{}", JSON.toJSONString(WpPostsDocument)));*/
            log.info("【保存索引】：{}",JSON.toJSONString(WpPostsDocumentRepository.saveAll(Arrays.asList(WpPostsDocuments))));
        }
    }

    @Override
    public void delete(String id) {
        WpPostsDocumentRepository.deleteById(id);
    }

    @Override
    public void deleteAll() {
        WpPostsDocumentRepository.deleteAll();
    }

    @Override
    public WpPostsDocument getById(String id) {
        return WpPostsDocumentRepository.findById(id).get();
    }

    @Override
    public List<WpPostsDocument> getAll() {
        List<WpPostsDocument> list = new ArrayList<>();
        WpPostsDocumentRepository.findAll().forEach(list::add);
        return list;
    }

}
